<template>
  <div id="edi">
    <div id="e" ref="editor"></div>
  </div>
</template>

<script>
import E from "wangeditor";
export default {
  components: {},
  model: {
    prop: "desc",
    event: "change",
  },
  props: {
    desc: String,
    //业务中我们经常会有添加操作和修改操作，添加操作时，我们需清除上一操作留下的缓存
    isClear: Boolean,
  },
  data() {
    return {
      content: "",
      editor: "",
    };
  },
  computed: {},
  watch: {
    isClear(val) {
      if (val) {
        this.editor.txt.clear();
      }
    },
    desc: {
      immediate: true,
      handler(value) {
        if (this.editor) {
          if (value != this.editor.txt.html()) {
            this.editor.txt.html(value);
            this.content = value;
            this.editor.selection.moveCursor(
              this.editor.$textElem.elems[0],
              false
            );
          }
        }
      },
    },
  },
  mounted() {
    this.initE();
  },
  activated() {},
  methods: {
    //清除修改器缓存
    clearFun() {
      this.editor.txt.clear();
    },
    //初始化
    initE() {
      this.editor = new E(this.$refs.editor);
      let that = this;
      this.editor.config.onchange = (html) => {
        this.info_ = html;
        this.$emit("change", this.info_);
      };
      this.editor.config.lineHeights = ["1", "1.15", "1.6", "2", "2.5", "3"];
      this.editor.config.customUploadImg = function (resultFiles, insertImgFn) {
        that
          .uploadImgReq(resultFiles[0])
          .then((res) => {
            insertImgFn(that.$img(res));
            console.log(res);
          })
          .catch((err) => {
            that.errorHandler(err);
            console.log(err);
          });
      };
      this.editor.config.customUploadVideo = function (
        resultFiles,
        insertVideoFn
      ) {
        that
          .uploadvideoReq(resultFiles[0])
          .then((res) => {
            insertVideoFn(that.$img(res));
            console.log(res);
          })
          .catch((err) => {
            that.errorHandler(err);
            console.log(err);
          });
      };
      this.editor.config.pasteFilterStyle = false;
      this.editor.config.menus = [
        "head", // 标题
        "bold", // 粗体
        "fontSize", // 字号
        // 'fontName', // 字体
        "italic", // 斜体
        "underline", // 下划线
        "strikeThrough", // 删除线
        "foreColor", // 文字颜色
        "backColor", // 背景颜色
        "lineHeight", //行高
        "link", // 插入链接
        "list", // 列表
        "justify", // 对齐方式
        "quote", // 引用
        "emoticon", // 表情
        "image", // 插入图片
        "table", // 表格
        "undo", // 撤销
        "redo", // 重复
        "video", //视频
      ];
      this.editor.config.pasteTextHandle = function (pasteStr) {
        // console.log(pasteStr, 111);

        let str = pasteStr.replace(
          /\<p/gi,
          '<p style="font-size: 13px !important;"'
        );
        str = str.replace(/\<h[1-6]/gi, "<h4");
        str = str.replace(/h[1-6]\>/gi, "h4>");
        str = str.replace(/\<div/gi, '<p style="font-size: 13px !important;"');

        // console.log(str, 2222);
        return str;

        /* var content = pasteStr.replace(
          /<img[^>]*>/gi,
          function (match, capture) {
            var match = match.replace(
              /(style="(.*?)")|(width="(.*?)")|(height="(.*?)")/gi,
              "style='height:auto;max-width:100%;'"
            );
            return match;
          }
        ); */
        /* pasteStr = pasteStr.replaceAll(
          /font-size:\s*(\d+)px/g,
          "font-size: 13px !important"
        );
        console.log(pasteStr);
        return '<p style="font-size: 13px !important;">' + pasteStr + "</p>"; */
      };
      this.editor.config.uploadImgMaxSize = 1 * 1024 * 1024;
      this.editor.config.showFullScreen = false;
      this.editor.config.showLinkImg = false;
      this.editor.config.showLinkVideo = false;
      this.editor.create();
      if (this.content) {
        this.editor.txt.html(this.content);
      } else {
        this.editor.txt.clear();
      }
    },
    async uploadImgReq(formdata) {
      try {
        let imgRes = await this.request({
          url: "/uploads/files",
          method: "post",
          dataType: "blob",
          loading: true,
          data: {
            img: formdata,
          },
        });
        return Promise.resolve(imgRes.content.img);
      } catch (error) {
        console.log(error);
        return Promise.reject(error);
      }
    },
    async uploadvideoReq(formdata) {
      try {
        let imgRes = await this.request({
          url: "/uploads/files",
          method: "post",
          dataType: "blob",
          loading: true,
          data: {
            temp_video: formdata,
          },
        });
        return Promise.resolve(imgRes.content.img);
      } catch (error) {
        console.log(error);
        return Promise.reject(error);
      }
    },
  },
};
</script>

<style lang="scss">
#edi {
  min-width: 350px;
  position: relative;
  z-index: 101;
}
.w-e-text-container {
  height: 500px !important; /*!important是重点，因为原div是行内样式设置的高度300px*/
}
</style>
